<template>
  <el-dialog title="批量修改" @close="onClose" :visible="isPop" width="400px" @open="onOpen">
    <el-form ref="form" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="已选择人数：">
        <span>{{ list.length }}人</span>
      </el-form-item>
      <el-form-item label="待修改属性：" prop="key">
        <el-select v-model="form.key" @change="onChange">
          <el-option v-for="item in modifiableAttribute" :key="item.key" :label="item.name" :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="nowType == 'number'" label="待修改金额：" prop="money">
        <el-input type="number" class="inputNumber" v-model="form.money"></el-input>
      </el-form-item>
      <el-form-item v-else-if="nowType == 'input'" label="待修改值：" prop="input">
        <el-input class="inputNumber" v-model="form.input"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onAffirm" :loading="loading">确 定</el-button>
    </template>
  </el-dialog>
</template>
<script>
export default {
  name: "batchEditPop",
  props: {
    isPop: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    },
    modifiableAttribute: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {},
      rules: {
        key: { required: true, message: "请选择修改的属性" },
        money: { required: true, message: "请输入修改的金额" },
        input: { required: true, message: "请输入修改的值" }
      },

      loading: false,
      nowType: "input"
    };
  },
  methods: {
    onOpen() {
      this.$nextTick(this.$refs.form?.clearValidate);
      this.form = {};
    },
    onClose() {
      this.$emit("update:isPop", false);
    },
    onClick() {
      this.onClose();
      this.$emit("affirm", this.checked);
    },
    onChange(e) {
      const o = this.modifiableAttribute.find(item => item.key == e);
      this.nowType = o?.type;
    },
    verify() {
      return new Promise((resolve, reject) => {
        this.$refs.form?.validate(valid => {
          if (valid) resolve();
          else reject();
        });
      });
    },
    async onAffirm() {
      try {
        this.loading = true;
        await this.verify();
        setTimeout(() => {
          // 因数据量比较大, 先等浏览器渲染loading后在执行
          const { key, money, input } = this.form;
          const type = this.nowType;
          this.$emit("affirm", {
            key,
            value: type == "input" ? input : money,
            type,
            fn: () => {
              this.loading = false;
            }
          });
        }, 100);
      } catch {
        this.loading = false;
      }
    }
  }
};
</script>
